import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import $bus from '@/eventBus';
import loadConfig from '@/config';
import { getStore, errorTips } from '@/utils/utils';
/**
 * http 请求
 *
 */
const mode = import.meta.env.VITE_MODE_ENV;
const http = ({
    url = '',
    method = 'post', //请求方式
    headers = {}, //请求头
    query = {}, //
    data = {}, //
    loading = true,
    other = false,
    // responseType = 'json',//
    timeout = 60 * 1000, //
    progressCallBack = (a: any) => {},
}) => {
    loadConfig.loading.value = loading;

    const axiosParams: AxiosRequestConfig = {
        url: mode === 'prod' ? import.meta.env[other ? 'VITE_CONFIG_BASE_URL' : 'VITE_BASE_URL'] + url : url,
        method,
        params: query,
        data,
        // responseType,
        timeout,
        headers: {
            Authorization: `${getStore('sign_admin_tokenType')} ${getStore('sign_admin_token')}`,
            ...headers,
        },

        onUploadProgress: (progressEvent: any) => {
            if (typeof progressCallBack === 'function') {
                progressCallBack(progressEvent);
            }
        },
    };

    return axios
        .request(axiosParams)
        .then(res => {
            loadConfig.loading.value = false;
            const resData = res.data || {};
            const { success, code, msg, status } = resData;

            if (code != 1) {
                $bus.emit('codeErrorHandle', code);

                return Promise.resolve(resData);
            }

            return Promise.resolve(resData);
        })
        .catch(err => {
            loadConfig.loading.value = false;
            $bus.emit('httpErrorHandle', err);
            return Promise.resolve(err);
        });
};

export default http;
